/**
 * 清空 MongoDB 数据脚本
 * 用于清理 MongoDB 中的所有数据
 */

import { connectMongoDB } from '../config/mongodb';
import { 
  User, 
  OCRRecord, 
  MedicalAlert, 
  SystemLog, 
  MedicalEquipment, 
  DrugInfo 
} from '../models/mongodb-schemas';

class MongoDBCleaner {
  
  /**
   * 清空所有集合
   */
  async clearAllCollections(): Promise<void> {
    try {
      console.log('🧹 开始清空 MongoDB 数据...');
      
      // 连接数据库
      await connectMongoDB();
      
      const collections = [
        { name: 'User', model: User },
        { name: 'OCRRecord', model: OCRRecord },
        { name: 'MedicalAlert', model: MedicalAlert },
        { name: 'SystemLog', model: SystemLog },
        { name: 'MedicalEquipment', model: MedicalEquipment },
        { name: 'DrugInfo', model: DrugInfo }
      ];
      
      for (const collection of collections) {
        try {
          const model = collection.model as any;
          const count = await model.countDocuments();
          if (count > 0) {
            await model.deleteMany({});
            console.log(`  ✅ 清空 ${collection.name}: ${count} 条记录`);
          } else {
            console.log(`  - ${collection.name}: 已为空`);
          }
        } catch (error) {
          console.error(`  ❌ 清空 ${collection.name} 失败:`, error);
        }
      }
      
      console.log('✅ MongoDB 数据清空完成');
      
    } catch (error) {
      console.error('❌ 清空数据失败:', error);
      throw error;
    }
  }

  /**
   * 清空特定集合
   */
  async clearCollection(collectionName: string): Promise<void> {
    try {
      await connectMongoDB();
      
      switch (collectionName.toLowerCase()) {
        case 'users':
          const userCount = await User.countDocuments();
          await User.deleteMany({});
          console.log(`✅ 清空用户集合: ${userCount} 条记录`);
          break;
          
        case 'alerts':
          const alertCount = await MedicalAlert.countDocuments();
          await MedicalAlert.deleteMany({});
          console.log(`✅ 清空告警集合: ${alertCount} 条记录`);
          break;
          
        case 'ocr':
          const ocrCount = await OCRRecord.countDocuments();
          await OCRRecord.deleteMany({});
          console.log(`✅ 清空OCR记录集合: ${ocrCount} 条记录`);
          break;
          
        case 'logs':
          const logCount = await SystemLog.countDocuments();
          await SystemLog.deleteMany({});
          console.log(`✅ 清空系统日志集合: ${logCount} 条记录`);
          break;
          
        case 'equipment':
          const equipCount = await MedicalEquipment.countDocuments();
          await MedicalEquipment.deleteMany({});
          console.log(`✅ 清空设备集合: ${equipCount} 条记录`);
          break;
          
        default:
          console.error(`❌ 未知的集合名称: ${collectionName}`);
          return;
      }
      
    } catch (error) {
      console.error(`❌ 清空集合 ${collectionName} 失败:`, error);
      throw error;
    }
  }

  /**
   * 获取当前数据统计
   */
  async getDataStats(): Promise<void> {
    try {
      await connectMongoDB();
      
      console.log('📊 当前数据统计:');
      
      const userCount = await User.countDocuments();
      const alertCount = await MedicalAlert.countDocuments();
      const ocrCount = await OCRRecord.countDocuments();
      const logCount = await SystemLog.countDocuments();
      const equipCount = await MedicalEquipment.countDocuments();
      const drugCount = await DrugInfo.countDocuments();
      
      console.log(`  - 用户: ${userCount}`);
      console.log(`  - 医疗告警: ${alertCount}`);
      console.log(`  - OCR记录: ${ocrCount}`);
      console.log(`  - 系统日志: ${logCount}`);
      console.log(`  - 医疗设备: ${equipCount}`);
      console.log(`  - 药品信息: ${drugCount}`);
      
      const total = userCount + alertCount + ocrCount + logCount + equipCount + drugCount;
      console.log(`  - 总计: ${total} 条记录`);
      
    } catch (error) {
      console.error('❌ 获取数据统计失败:', error);
      throw error;
    }
  }
}

// 执行清理的主函数
async function runCleaner() {
  const cleaner = new MongoDBCleaner();
  
  // 获取命令行参数
  const args = process.argv.slice(2);
  const command = args[0];
  const collection = args[1];
  
  try {
    if (command === 'stats') {
      await cleaner.getDataStats();
    } else if (command === 'clear') {
      if (collection) {
        await cleaner.clearCollection(collection);
      } else {
        // 确认清空所有数据
        console.log('⚠️ 确认清空所有 MongoDB 数据？这个操作不可恢复！');
        console.log('请在5秒内按 Ctrl+C 取消...');
        
        await new Promise(resolve => setTimeout(resolve, 5000));
        await cleaner.clearAllCollections();
      }
    } else {
      console.log('📖 使用说明:');
      console.log('  node dist/scripts/clear-mongodb.js stats          # 查看数据统计');
      console.log('  node dist/scripts/clear-mongodb.js clear          # 清空所有数据');
      console.log('  node dist/scripts/clear-mongodb.js clear users    # 清空用户数据');
      console.log('  node dist/scripts/clear-mongodb.js clear alerts   # 清空告警数据');
      console.log('  node dist/scripts/clear-mongodb.js clear ocr      # 清空OCR记录');
      console.log('  node dist/scripts/clear-mongodb.js clear logs     # 清空系统日志');
      console.log('  node dist/scripts/clear-mongodb.js clear equipment # 清空设备数据');
    }
    
    process.exit(0);
  } catch (error) {
    console.error('💥 操作失败:', error);
    process.exit(1);
  }
}

// 如果直接运行此脚本，则执行清理
if (require.main === module) {
  runCleaner();
}

export { MongoDBCleaner };